package com.starry.push.netty.manager;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.starry.push.netty.domain.LogWsConnect;
import com.starry.push.netty.service.LogWsConnectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.List;

/**
 * @author WuChao
 * @version 1.0
 * @date 2020/6/18 15:23
 */
@Component
@Slf4j
public class ShutdownManager {

    @Autowired
    private LogWsConnectService wsConnectService;


    @PreDestroy
    public void destroy()
    {
        channelRemove();
        shutdownAsyncManager();
    }

    /**
     * 停止异步执行任务
     */
    private void shutdownAsyncManager()
    {
        try
        {
            log.info("\033[32;1m"+"====关闭后台任务任务线程池===="+"\033[0m");
            AsyncManager.me().shutdown();
        }
        catch (Exception e)
        {
            log.error(e.getMessage(), e);
        }
    }

    private void channelRemove() {

        List<LogWsConnect> connects = wsConnectService.list(new QueryWrapper<LogWsConnect>()
                .eq(LogWsConnect.COL_STATUS, 1)
        );
        if (CollectionUtils.isNotEmpty(connects)) {
            connects.forEach(logWsConnect->{
                logWsConnect.setStatus(3);
            });
            wsConnectService.updateBatch(connects);
        }

    }



}
